<template>
	<view class="container">
		<view class="form-group">
			<text class="label">名称</text>
			<input class="input" v-model="formData.name" placeholder="请输入名称"/>
		</view>
		
		<view class="form-group">
			<text class="label">所在城市</text>
			<picker mode="selector" :range="cityList" range-key="name" @change="onCityChange">
				<view class="picker-box">
					<text class="picker-value">{{formData.city_id ? (cityList.find(city => Number(city.id) == Number(formData.city_id))?.name || '请选择城市') : '请选择城市'}}</text>
				</view>
			</picker>
		</view>
		
		<view class="form-group">
			<text class="label">封面图</text>
			<view class="upload-image" @click="uploadImage('cover')" v-if="!formData.cover_url">
				<text class="iconfont icon-add"></text>
				<text class="tip">点击上传图片</text>
			</view>
			<view class="preview-box" v-else>
				<image :src="formData.cover_url" mode="aspectFill"></image>
				<view class="delete-btn" @click="deleteImage('cover')">
					<text class="iconfont icon-close"></text>
				</view>
			</view>
		</view>
		
		<view class="form-group">
			<text class="label">营业时间</text>
			<view class="radio-group">
				<radio-group @change="onTimeTypeChange">
					<label>
						<radio value="0" :checked="!formData.is_24h"/>
						<text>自定义时间</text>
					</label>
					<label>
						<radio value="1" :checked="formData.is_24h"/>
						<text>24小时营业</text>
					</label>
				</radio-group>
			</view>
		</view>
		
		<view class="form-group time-group" v-if="!formData.is_24h">
			<view class="time-picker-group">
				<view class="time-item">
					<text class="time-label">开始时间</text>
					<picker mode="time" :value="formData.start_time" @change="onStartTimeChange">
						<view class="picker-box">
							<text class="picker-value">{{formData.start_time}}</text>
						</view>
					</picker>
				</view>
				<text class="separator">至</text>
				<view class="time-item">
					<text class="time-label">结束时间</text>
					<picker mode="time" :value="formData.end_time" @change="onEndTimeChange">
						<view class="picker-box">
							<text class="picker-value">{{formData.end_time}}</text>
						</view>
					</picker>
				</view>
			</view>
		</view>
		
		<view class="form-group">
			<text class="label">所在地址</text>
			<view class="address-box">
				<textarea class="textarea" v-model="formData.address" placeholder="请输入详细地址" />
				<button class="choose-location-btn" @click="chooseLocation">定位</button>
			</view>
		</view>
		
		<view class="form-group">
			<text class="label">联系方式</text>
			<view class="contact-box">
				<input class="input" v-model="formData.contact" placeholder="请输入联系方式" @input="checkManagerStatus($event.detail.value)"/>
				<button class="set-shoper-btn" @click="setManager">{{isManager ? '取消店长' : '设置店长'}}</button>
			</view>
		</view>
		
		<view class="form-group">
			<text class="label">显示状态</text>
			<view class="switch-group">
				<switch :checked="formData.status === 1" @change="onStatusChange" color="#07c160"/>
				<text class="switch-text">{{formData.status === 1 ? '显示' : '不显示'}}</text>
			</view>
		</view>
		
		<view class="form-group" v-if="isEdit">
			<text class="label">门店二维码</text>
			<view class="qrcode-box">
				<button class="qrcode-btn" @click="downloadQrcode">下载二维码</button>
			</view>
		</view>
		
		<view class="btn-group">
			<button class="save-btn" @click="submit">确定</button>
			<button class="delete-btn" v-if="isEdit" @click="confirmDelete">删除</button>
		</view>
	</view>
</template>

<script>
import mixinsAuth from '@/mixins/auth.js'
import mixinsCommon from '@/mixins/common.js'
import { uploadImage } from '@/service/api/common.js'
import { compressImage } from '@/common/util.js'
import { getShopDetail, saveShop, deleteShop, getShopQrcode, setShoperByPhone, getShoperByPhone } from '@/service/api/shop.js'
import { getCityList } from '@/service/api/city.js'

export default {
	mixins: [mixinsCommon, mixinsAuth],
	data() {
		return {
			isEdit: false,
			qrcodeUrl: '',
			isManager: false,
			cityList: [],
			formData: {
				name: '',
				city_id: '',
				cover_url: '',
				is_24h: 0,
				start_time: '09:00',
				end_time: '21:00',
				address: '',
				longitude: 0,
				latitude: 0,
				contact: '',
				status: 1
			}
		}
	},
	onLoad(options) {
		// 设置导航栏标题
		uni.setNavigationBarTitle({
			title: options.id ? '编辑门店' : '新增门店'
		})
		
		// 获取城市列表
		this.loadCityList()
		
		if(options.id) {
			this.isEdit = true
			this.loadShopData(options.id)
		}
	},
	methods: {
		loadCityList() {
			uni.showLoading({
				title: '加载中'
			})
			getCityList().then(([err, res]) => {
				uni.hideLoading()
				if (!err && res) {
					this.cityList = res
				} else {
					uni.showToast({
						title: '城市列表加载失败',
						icon: 'none'
					})
				}
			})
		},
		loadShopData(id) {
			uni.showLoading({
				title: '加载中'
			})
			getShopDetail(id).then(([err, res]) => {
				uni.hideLoading()
				if (!err && res) {
					// 过滤掉state字段，只保留需要的字段
					const { 
						id, name, city_id, cover_url, is_24h, 
						start_time, end_time, address, 
						longitude, latitude, contact 
					} = res
					this.formData = {
						id, name, city_id, cover_url, is_24h,
						start_time: start_time?.replace(/(\d{2})(\d{2})/, '$1:$2') || '09:00',
						end_time: end_time?.replace(/(\d{2})(\d{2})/, '$1:$2') || '21:00',
						address, longitude, latitude, contact,
						status: res.status
					}
					
					// 如果有联系方式，检查是否是店长
					if (contact) {
						this.checkManagerStatus(contact)
					}
				} else {
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
				}
			})
		},
		onTimeTypeChange(e) {
			this.formData.is_24h = Number(e.detail.value)
			if(this.formData.is_24h) {
				this.formData.start_time = '00:00'
				this.formData.end_time = '23:59'
			}
		},
		onStartTimeChange(e) {
			this.formData.start_time = e.detail.value
		},
		onEndTimeChange(e) {
			this.formData.end_time = e.detail.value
		},
		chooseLocation() {
			uni.chooseLocation({
				success: (res) => {
					this.formData.address = res.address
					this.formData.longitude = res.longitude
					this.formData.latitude = res.latitude
				}
			})
		},
		uploadImage(type) {
			uni.chooseImage({
				count: 1, // 1张
				sizeType: ['compressed'], // 压缩图
			}).then(([err, res]) => {
				console.log('chooseImage', err, res)
				if (!err) {
					compressImage(res.tempFiles[0], 1800, 2700).then(([err, res]) => {
						console.log('compressImage', err, res)
						if (!err) {
							uploadImage(res).then(([err, res]) => {
								console.log('uploadImage', err, res)
								if (!err) {
									this.formData.cover_url = res.fullurl
								}
							})
						}
					})
				}
			})
		},
		deleteImage(type) {
			this.formData.cover_url = ''
		},
		submit() {
			if (!this.formData.name) {
				uni.showToast({
					title: '请输入门店名称',
					icon: 'none'
				})
				return
			}
			
			if (!this.formData.city_id) {
				uni.showToast({
					title: '请选择所在城市',
					icon: 'none'
				})
				return
			}
			
			if (!this.formData.cover_url) {
				uni.showToast({
					title: '请上传门店封面',
					icon: 'none'
				})
				return
			}
			
			if (!this.formData.address) {
				uni.showToast({
					title: '请输入门店地址',
					icon: 'none'
				})
				return
			}
			
			if (!this.formData.contact) {
				uni.showToast({
					title: '请输入联系方式',
					icon: 'none'
				})
				return
			}
			
			uni.showLoading({
				title: '保存中'
			})
			
			saveShop(this.formData).then(([err, res]) => {
				uni.hideLoading()
				
				// 直接判断是否有返回值
				if (!err ) {
					uni.showToast({
						title: '保存成功',
						icon: 'success',
						duration: 1500
					})
					
					// 获取页面实例
					const pages = getCurrentPages()
					const prevPage = pages[pages.length - 2]
					
					// 通知上一个页面刷新数据
					if (prevPage && prevPage.$vm) {
						// 调用列表页面的刷新方法
						prevPage.$vm.loadData(true)
					}
					
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 1500)
				} else {
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					})
				}
			})
		},
		confirmDelete() {
			uni.showModal({
				title: '提示',
				content: '确定要删除该门店吗？',
				success: (res) => {
					if (res.confirm) {
						this.deleteShop()
					}
				}
			})
		},
		deleteShop() {
			uni.showLoading({
				title: '删除中'
			})
			
			deleteShop(this.formData.id).then(([err, res]) => {
				uni.hideLoading()
				
				if (!err) {
					uni.showToast({
						title: '删除成功',
						icon: 'success',
						duration: 1500
					})
					
					// 获取页面实例
					const pages = getCurrentPages()
					const prevPage = pages[pages.length - 2]
					
					// 通知上一个页面刷新数据
					if (prevPage && prevPage.$vm) {
						prevPage.$vm.loadData(true)
					}
					
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 1500)
				} else {
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					})
				}
			})
		},
		downloadQrcode() {
			if (!this.formData.id) {
				uni.showToast({
					title: '请先保存门店信息',
					icon: 'none'
				})
				return
			}
			
			uni.showLoading({
				title: '生成中'
			})
			
			getShopQrcode(this.formData.id).then(([err, res]) => {
				uni.hideLoading()
				if (!err) {
					// 下载图片
          let url = 'https://ty.bootjs.cn'+res
          //url = 'https://ty.bootjs.cn/uploads/qrcode/202504/67f5e2883fa612.94834408.jpg';

					uni.downloadFile({
						url: url,
						success: (downloadRes) => {
							if (downloadRes.statusCode === 200) {
								// 保存图片到相册
								uni.saveImageToPhotosAlbum({
									filePath: downloadRes.tempFilePath,
									success: () => {
										uni.showToast({
											title: '保存成功',
											icon: 'success'
										})
									},
									fail: () => {
										uni.showToast({
											title: '保存失败',
											icon: 'none'
										})
									}
								})
							}
						},
						fail: () => {
							uni.showToast({
								title: '下载失败',
								icon: 'none'
							})
						}
					})
				} else {
					uni.showToast({
						title: '生成失败',
						icon: 'none'
					})
				}
			})
		},
		onStatusChange(e) {
			this.formData.status = e.detail.value ? 1 : 0
		},
		checkManagerStatus(phone) {
			if (!phone) return
			
			getShoperByPhone(phone).then(([err, res]) => {
				if (!err) {
					this.isManager = res.is_manager
				}
			})
		},
		setManager() {
			if (!this.formData.contact) {
				uni.showToast({
					title: '请先输入联系方式',
					icon: 'none'
				})
				return
			}
			
			uni.showLoading({
				title: this.isManager ? '取消中' : '设置中'
			})
			
			if (this.isManager) {
				// 取消店长
				setShoperByPhone(this.formData.contact, true).then(([err, res]) => {
					uni.hideLoading()
					if (!err) {
						this.isManager = false
						uni.showToast({
							title: '取消成功',
							icon: 'success'
						})
					} else {
						uni.showToast({
							title: err.msg || '取消失败',
							icon: 'none'
						})
					}
				})
			} else {
				// 设置为店长
				setShoperByPhone(this.formData.contact).then(([err, res]) => {
					uni.hideLoading()
					if (!err) {
						this.isManager = true
						uni.showToast({
							title: '设置成功',
							icon: 'success'
						})
					} else {
						uni.showToast({
							title: err.msg || '设置失败',
							icon: 'none'
						})
					}
				})
			}
		},
		onCityChange(e) {
			const index = e.detail.value;
			this.formData.city_id = Number(this.cityList[index].id);
		}
	}
}
</script>

<style lang="scss">
page {
	background-color: #f8f8f8;
}

.container {
	padding: 20rpx;
	padding-bottom: 120rpx;
	
	.form-group {
		background-color: #FFFFFF;
		padding: 20rpx 30rpx;
		margin-bottom: 2rpx;
		
		.label {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 20rpx;
			display: block;
		}
		
		.input {
			height: 70rpx;
			line-height: 70rpx;
			font-size: 28rpx;
			color: #333;
			width: 100%;
		}
		
		.address-box {
			display: flex;
			align-items: flex-start;
			
			.textarea {
				flex: 1;
				height: 160rpx;
				font-size: 28rpx;
				color: #333;
				line-height: 1.5;
				padding: 20rpx;
				box-sizing: border-box;
				border: 1px solid #eee;
				border-radius: 8rpx;
				margin-right: 20rpx;
			}
			
			.choose-location-btn {
				width: 120rpx;
				height: 70rpx;
				line-height: 70rpx;
				text-align: center;
				background-color: #4a5464;
				color: #fff;
				border-radius: 8rpx;
				font-size: 28rpx;
			}
		}
		
		.upload-image {
			width: 200rpx;
			height: 200rpx;
			border: 1px dashed #ddd;
			border-radius: 8rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			
			.iconfont {
				font-size: 48rpx;
				color: #999;
				margin-bottom: 10rpx;
			}
			
			.tip {
				font-size: 24rpx;
				color: #999;
			}
		}
		
		.preview-box {
			position: relative;
			width: 200rpx;
			height: 200rpx;
			
			image {
				width: 100%;
				height: 100%;
				border-radius: 8rpx;
			}
			
			.delete-btn {
				position: absolute;
				top: -20rpx;
				right: -20rpx;
				width: 40rpx;
				height: 40rpx;
				background: rgba(0,0,0,0.5);
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				
				.iconfont {
					color: #fff;
					font-size: 24rpx;
				}
			}
		}
		
		.radio-group {
			label {
				margin-right: 40rpx;
				font-size: 28rpx;
				
				radio {
					transform: scale(0.8);
					margin-right: 6rpx;
				}
			}
		}
		
		&.time-group {
			padding: 0 30rpx;
			background: transparent;
		}
		
		.time-picker-group {
			display: flex;
			align-items: center;
			justify-content: space-between;
			background: #fff;
			padding: 30rpx;
			border-radius: 8rpx;
			
			.time-item {
				flex: 1;
				
				.time-label {
					font-size: 24rpx;
					color: #666;
					margin-bottom: 10rpx;
					display: block;
				}
				
				.picker-box {
					height: 70rpx;
					line-height: 70rpx;
					padding: 0 20rpx;
					background: #f8f8f8;
					border-radius: 8rpx;
					text-align: center;
					
					.picker-value {
						font-size: 32rpx;
						color: #333;
						font-weight: bold;
					}
				}
			}
			
			.separator {
				padding: 20rpx;
				font-size: 28rpx;
				color: #999;
				margin-top: 20rpx;
			}
		}
		
		.switch-group {
			display: flex;
			align-items: center;
			
			.switch-text {
				margin-left: 20rpx;
				font-size: 28rpx;
				color: #333;
			}
		}
		
		.contact-box {
			display: flex;
			align-items: center;
			
			.input {
				flex: 1;
				margin-right: 20rpx;
			}
			
			.set-shoper-btn {
				width: 240rpx;
				height: 70rpx;
				line-height: 70rpx;
				text-align: center;
				background-color: #07c160;
				color: #fff;
				border-radius: 35rpx;
				font-size: 28rpx;
			}
		}
	}
	
	.btn-group {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 20rpx;
		background: #fff;
		display: flex;
		justify-content: space-between;
		box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
		
		.save-btn, .delete-btn {
			width: 340rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-radius: 8rpx;
			font-size: 32rpx;
		}
		
		.save-btn {
			background-color: #07c160;
			color: #FFFFFF;
		}
		
		.delete-btn {
			background-color: #fff;
			color: #ff4d4f;
			border: 1px solid #ff4d4f;
		}
	}
	
	.qrcode-box {
		margin-top: 10rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		
		.qrcode-btn {
			width: 300rpx;
			height: 70rpx;
			line-height: 70rpx;
			text-align: center;
			background-color: #07c160;
			color: #fff;
			border-radius: 35rpx;
			font-size: 28rpx;
		}
	}
}
</style> 